<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="1300" destroy-on-close @closed="$emit('closed')" align-center :close-on-click-modal="false">
		<el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="120px" label-position="right">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="生产计划单" prop="plan_id">
                        <el-input v-model="plan_code" placeholder="请选择生产计划单" readonly @click="checkPlan"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="入库单号" prop="entry_code">
                        <el-input v-model="form.entry_code" placeholder="入库单号(不填写自动生成)" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="入库日期" prop="entry_date">
                        <el-date-picker v-model="form.entry_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" />
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="6">
                    <el-form-item label="供应商" prop="supplier_id">
                        <el-select v-model="form.supplier_id" placeholder="请选择" filterable>
                            <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col> -->
                <el-col :span="6">
                    <el-form-item label="入库仓库" prop="ware_id">
                        <el-select v-model="ware_id" filterable style="width: 100%" placeholder="仓库" @change="wareChange" clearable>
                            <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="倒冲领料" prop="is_inverted">
                        <el-switch v-model="form.is_inverted" :active-value="1" :inactive-value="0"></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="原料仓库" prop="material_ware" v-if="form.is_inverted == 1">
                        <el-select v-model="form.material_ware" filterable style="width: 100%" placeholder="仓库" clearable>
                            <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="附件" prop="enclosure">
                <sc-upload-file v-model="form.enclosure" :limit="1">
                    <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
                </sc-upload-file>
            </el-form-item>
            <el-col :span="12">
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="备注" type="textarea" clearable></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="产品清单" prop="detail">
                    <el-button type="primary" size="small" icon="el-icon-plus" @click="checkGoods">选择商品</el-button>
                    <sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" placeholder="暂无数据" height="250" hideAdd>
                        <el-table-column prop="goods_code" label="商品编码" align="center">
                            <template #default="scope">
                                {{scope.row.goods_code}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="goods_name" label="商品名称" align="center">
                            <template #default="scope">
                                {{scope.row.goods_name}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="goods_model" label="商品型号" align="center">
                            <template #default="scope">
                                {{scope.row.goods_model}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="goods_spec" label="商品规格" align="center">
                            <template #default="scope">
                                {{scope.row.goods_spec}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="unit_name" label="单位" align="center">
                            <template #default="scope">
                                {{scope.row.unit_name}}
                            </template>
                        </el-table-column>
                        <el-table-column label="生产数量" prop="plan_number" align="center">
                        </el-table-column>
                        <el-table-column label="可入库数量" prop="can_number" align="center">
                        </el-table-column>
                        <el-table-column label="本次入库数量" prop="number" align="center">
                            <template #default="scope">
                                <el-input v-model="scope.row.number" placeholder="本次入库数量" @focus="onFocus($event)" @input="houseInput(scope.row)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="仓库" align="center">
                            <template #default="scope">
                                <el-select v-model="scope.row.ware_id" filterable style="width: 100%" placeholder="仓库">
                                    <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                    </sc-form-table>
                </el-form-item>
            </el-col>
        </el-form>
		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
    <select-plan v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false" :query="{status:1}"></select-plan>
</template>

<script>
import selectPlan from '../plan/selectPlan.vue';
export default {
    components: { selectPlan },
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增入库单',
				edit: '编辑入库单',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
			//表单数据
			form: {
                id: "",
                entry_code: "",
                entry_date: this.moment().format('YYYY-MM-DD'),
                enclosure: "",
                remark: "",
                detail: [],
                plan_id: "",
                is_inverted: "",
                material_ware: "",
			},
            plan_code: "",
            ware_id: "",
			//验证规则
			rules: {
				plan_id: [{ required: true, message: '请选择销售' }],
			},
            dialog: {
                save: false,
            },
            applyList: [],
            wareList: [],
		}
	},
	mounted() {
        this.getApply();
        this.getWare()
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = [];
					if (this.form.id) {
						res = await this.$API.production.inhouse.edit.post(this.form);
					} else {
						res = await this.$API.production.inhouse.add.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 1) {
						this.$emit('success', this.form, this.mode)
						this.visible = false;
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", { type: 'error' })
					}
				} else {
					return false;
				}
			})
		},
        goProduction(data){
            this.disabled = true
            this.form.contract_id = data.id
            this.contract_code = data.contract_code
            let array = []
            data.product.map(item=>{
                array.push({
                    goods_id:item.goods_id,
                    goods_name:item.goods.goods_name,
                    goods_spec:item.goods.goods_spec,
                    goods_model:item.goods.goods_model,
                    unit_name:item.goods.unit.unit_name,
                    goods_code:item.goods.goods_code,
                })
                this.form.detail = array
            })
        },
		//表单注入数据
		async setData(data) {
            this.form.id = data.id
            var res = await this.$API.production.inhouse.detail.get({id:data.id});
            this.form.entry_code = res.data.entry_code
            this.form.plan_id = res.data.plan_id
            this.plan_code = res.data.plan.production_code
            this.form.entry_date = res.data.entry_date
            this.form.enclosure = res.data.enclosure
            this.form.remark = res.data.remark
            this.form.is_inverted = res.data.is_inverted
            this.form.material_ware = res.data.material_ware
            let array = []
            res.data.detail.map(item=>{
                array.push({
                    id:item.id,
                    goods_id:item.goods_id,
                    goods_code:item.goods && item.goods.goods_code,
                    goods_name:item.goods && item.goods.goods_name,
                    goods_spec:item.goods && item.goods.goods_spec,
                    goods_model:item.goods && item.goods.goods_model,
                    unit_name:item.goods && item.goods.unit.unit_name,
                    plan_number:item.plan_num.number,
                    can_number:item.plan_num.number - (item.plan_num.deliver_number + item.plan_num.enter_number),
                    number: item.number,
                    ware_id:item.ware_id
                })
            })
            this.form.detail = array
		},
        onFocus(event){
            event.target.select();
        },
        checkContract(){
            if(!this.disabled){
                this.dialog.contract = true
                this.$nextTick(() => {
                    this.$refs.contractDialog.open('add')
                })
            }
        },
        contractUpdate(data){
            this.form.contract_id = data.id
            this.contract_code = data.contract_code
            let array = []
            data.product.map(item=>{
                array.push({
                    goods_id:item.goods_id,
                    goods_name:item.goods.goods_name,
                    goods_spec:item.goods.goods_spec,
                    goods_model:item.goods.goods_model,
                    unit_name:item.goods.unit.unit_name,
                    goods_code:item.goods.goods_code,
                })
                this.form.detail = array
            })
        },
        // 选择商品
        checkGoods(e){
            this.dialog.goods = true
            this.$nextTick(() => {
                this.$refs.goodsDialog.open('add').setData(e)
            })
        },
        goodsUpdate(data){
            let array = []
            data.map((item)=>{
                array.push({
                    goods_id:item.id,
                    goods_name:item.goods_name,
                    goods_spec:item.goods_spec,
                    goods_model:item.goods_model,
                    unit_name:item.unit.unit_name,
                    goods_code:item.goods_code,
                })
            })
            let existingIds = this.form.detail.map(item => item.goods_id);
            for(let i = array.length - 1; i >= 0; i--){
                if(existingIds.includes(array[i].goods_id)){
                    array.splice(i, 1);
                }
            }
            this.form.detail = [...this.form.detail,...array]
        },
        // 供应商列表
        async getApply(){
            var res = await this.$API.apply.apply.all.get();
            this.applyList = res.data
        },
        // 获取仓库
        async getWare(){
            var res = await this.$API.goods.ware.all.get();
            this.wareList = res.data;
        },
        checkPlan(){
            this.dialog.save = true
            this.$nextTick(() => {
                this.$refs.saveDialog.open('add')
            })
        },
        handleSuccess(data){
            this.form.plan_id = data.id
            this.plan_code = data.production_code
            this.getDetail(data.id)
        },
        async getDetail(e){
            var res = await this.$API.production.plan.detail.get({id:e})
            let array = []
            res.data.detail.map(item=>{
                array.push({
                    id:item.id,
                    goods_id:item.goods_id,
                    goods_code:item.goods.goods_code,
                    goods_name:item.goods.goods_name,
                    goods_spec:item.goods.goods_spec,
                    goods_model:item.goods.goods_model,
                    unit_name:item.goods.unit&&item.goods.unit.unit_name,
                    plan_number:item.number,
                    can_number:item.number - item.deliver_number,
                })
            })
            this.form.detail = array
        },
        houseInput(row){
            if(row.number > row.can_number){
                this.$message.error("入库数量不能大于可入库数量")
                row.number = row.can_number
            }
        },
        wareChange(e){
            this.form.detail.map(item => item.ware_id = e)
        },
	}
}
</script>

<style></style>
